﻿Imports System.Net.Sockets
Imports System.Net
Imports System.Text
Imports System.Threading
Imports System.ComponentModel
Imports S7.Net




Public Class IMSocketTest

    Dim strconn As String, strsql As String
    Dim sqlc As SqlClient.SqlConnection
    Dim da As SqlClient.SqlDataAdapter
    Dim ds As New DataSet
    Dim dc As SqlClient.SqlCommand
    '定义两个窗体变量
    Dim s As Socket = Nothing
    Dim t As Thread
    '新建一个过程，用于处理接收到的Socket数据包
    '*****************************************【BEGIN】单线程Socket通讯，用于集智平衡通讯，存在缺陷**************************
    Public Delegate Function MyInvoke(str1 As String) '//定义一个委托事件


    Private Sub Form1_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        ' 为了防止用户不点击Stop直接退出， 而不能使线程结束， 则应在窗体的closing事件中， 加入如下代码
        Try
            s.Close()
            t.Abort()
        Catch
        End Try
    End Sub
    Function ERJINZHI(str As String)

        Dim btText() As Byte
        Dim strBin As String = ""
        Dim i As Integer
        btText = System.Text.Encoding.UTF8.GetBytes(str)
        For i = 0 To btText.Length - 1
            strBin = strBin & Convert.ToString(Int32.Parse(btText(i)), 2).PadLeft(8, "0")
        Next
        btText = System.Text.Encoding.UTF8.GetBytes(strBin)
        Return strBin
    End Function
    Function ConvertHexToTwo(str As String) As Byte()

        Dim TestArray() As String = Split(str) '将16进制数拆分为数组
        Dim hexBytes() As Byte
        ReDim hexBytes(TestArray.Length - 1)
        Dim i As Integer
        For i = 0 To TestArray.Length - 1
            hexBytes(i) = Val("&h" & TestArray(i)) '将16进制数转化为2进制
        Next
        Return hexBytes
    End Function
    Function ConvertHexTotest(str As String) As Byte()

        Dim TestArray() As String = Split(str) '将16进制数拆分为数组
        Dim hexBytes() As Byte
        ReDim hexBytes(TestArray.Length - 1)
        Dim i As Integer
        For i = 0 To TestArray.Length - 1
            hexBytes(i) = ("0x" & TestArray(i)) '将16进制数转化为2进制
        Next
        Return hexBytes
    End Function
    '以16进制存入字节数组
    Function ConvertHexToBytes(str As String) As Byte()

        Dim TestArray() As String = Split(str) '将16进制数拆分为数组
        Dim hexBytes() As Byte
        ReDim hexBytes(TestArray.Length - 1)
        Dim i As Integer
        For i = 0 To TestArray.Length - 1
            hexBytes(i) = Convert.ToByte(TestArray(i), 16) '将16进制数转化为字节
        Next
        Return hexBytes
    End Function

    Function ConvertBytesToHex(hexBytes() As Byte) As String
        Dim str As String = ""
        Dim TestArray() As String
        ReDim TestArray(hexBytes.Length - 1)
        Dim i As Integer
        For i = 0 To hexBytes.Length - 1
            TestArray(i) = hexBytes(i).ToString("X2") '将16进制数转化为2进制
            str = str & " " & TestArray(i)
        Next

        Return Mid(str, 2)
    End Function
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles socketclient_send_btn.Click
        Try
            Dim bytes(1024) As Byte
            Dim s = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            Dim localEndPoint As New IPEndPoint(IPAddress.Parse(Trim(socketclient_ip_txt.Text)), Trim(socketclient_port_txt.Text))
            s.Connect(localEndPoint)

            '     s.Send(ERJINZHI(socketclient_content_txt.Text))
            ' s.Send(Encoding.ASCII.GetBytes(socketclient_content_txt.Text))
            If CheckBox1.Checked Then
                s.Send(ConvertHexToBytes(socketclient_content_txt.Text))
            Else

                s.Send(Encoding.ASCII.GetBytes(socketclient_content_txt.Text))


            End If
            Dim TIMOUTA As DateTime = Now
            Do While (True)

                Dim data(10240) As Byte
                Dim datac(10240) As Byte
                Dim reclen As Integer = 1024
                s.ReceiveTimeout = 10
                reclen = s.Receive(datac)

                ReDim data(reclen)
                data = datac.Take(reclen).ToArray

                Dim stringData As String

                If CheckBox2.Checked Then

                    stringData = ConvertBytesToHex(data)
                Else
                    stringData = Encoding.UTF8.GetString(data)
                End If

                If Not (String.IsNullOrWhiteSpace(stringData)) Then
                    printinfo(stringData)
                    Exit Do
                End If

                If TIMOUTA.AddSeconds(10) < Now Then
                    printinfo("SystemInfo:信息获取超时")
                    Exit Do
                End If
            Loop
            s.Close()
            printinfo("SystemInfo:发送完毕")
        Catch ex As Exception

            printinfo("SystemInfo:发送异常，导致异常出现可能的情况：1、网络异常；2、连接异常；3、发送数据错误。 ")
            printinfo("SystemInfo: 异常信息：" & ex.ToString)

        End Try
    End Sub
    Function printinfo(str As String)
        socketclient_rec_list.AppendText(Chr(13) & str)
        socketclient_rec_list.ScrollToCaret()
    End Function

    '******************************************【END】单线程Socket通讯，用于集智平衡通讯，存在缺陷**************************

    '******************************************【BEGIN】S7直连代码******************************************************
    Private Sub Button4_Click(sender As Object, e As EventArgs)
        MsgBox(Remoteconnectplc("S71200", "192.168.11.100", "0", "1"))
    End Sub

    Dim db As Integer = 0 '//DB块号，读写I、Q、M时都为0，读写V区的时为1，读写DB块时按实际情况处理
    Dim startByteAdr As Integer = 0 ';//起始地址
    Dim DataAddress_Choise As DataType = DataType.Input ';//数据区域，如I、Q、M、V、DB

    Dim DataType_Choise_string As String = "Bool"
    Dim DataType_Choise As DataType
    Public Function Remoteconnectplc(plcchoice As String, plcip As String, plcrack As String, plcslot As String)

        If ((plcchoice <> "") And (plcip <> "") And (plcrack <> "") And (plcslot <> "")) Then

            Dim ip As String = plcip ';//PLC的IP地址
            Dim rack As String = Convert.ToInt16(plcrack) ';//机架号， 默认0
            Dim slot As Short = Convert.ToInt16(plcslot) '槽号， 默认0
            Select Case (plcchoice)

                Case "S7200 SMART"        ' //连接S7200 SMART，使用1200驱动
                    plc = New Plc(CpuType.S71200, ip, rack, slot)

                Case "S7200"
                    plc = New Plc(CpuType.S7200, ip, rack, slot)

                Case "S7300"
                    plc = New Plc(CpuType.S7300, ip, rack, slot)

                Case "S7400"
                    plc = New Plc(CpuType.S7400, ip, rack, slot)

                Case "S71200"
                    plc = New Plc(CpuType.S71200, ip, rack, slot)

                Case "S71500"
                    plc = New Plc(CpuType.S71500, ip, rack, slot)


            End Select

            plc.Open() '//连接PLC
            If (plc.IsConnected) Then

                Return "connect success"

            Else

                Return "connect fail params wrong"
                '//MessageBox.Show("PLC连接不成功,请检查PLC类型、IP地址、机架、插槽等是否正确!");
            End If
        Else

            Return "connect fail incomplete"
            '//MessageBox.Show("请完整的填写上述参数！");
        End If
    End Function
    Function breakconnect()
        plc.Close()
        If (Not plc.IsConnected) Then
            Return "已断开与PLC!"

        Else
            Return ("断开PLC失败!")
        End If
    End Function

    Function readdata(dbnumber As String, dbaddress As DataType, dbtypestring As String, startaddress As String, bitnumber As String)

        If (Not plc.IsConnected) Then
            Return ("请先建立连接！")
        End If
        If (dbnumber = "") Then
            Return ("请先填写DB块号！")

        Else
            db = Convert.ToInt32(dbnumber)
        End If
        If (startaddress = "") Then
            Return ("请先填写偏移量！")

        Else
            startByteAdr = Convert.ToInt32(startaddress) ';//读取数据起始地址

            Select Case dbtypestring

                Case "Bool"
                    Dim bit_number As Integer = Convert.ToInt32(bitnumber) ';//位号
                    '         //var result_bool = plc.Read(DataAddress_Choise, db, startByteAdr, VarType.Bit, 1);
                    '         //上面函数有bug，所以使用读取Byte函数，读取1个byte然后再计算出bit的值 

                    '         ///该函数用来读取任意类型、任意数量的变量，本程序中只读取1个字节
                    '///DataAddress_Choise：数据区
                    '///int db：DB块号， 读写I、Q、M时都为0， 读写V区的时为1， 读写DB块时按实际情况处理
                    '///int startByteAdr：起始地址
                    '///VarType.Byte：数据类型
                    '///int varCount：读取数量， 本程序默认1， 实际应用可视具体情况修改
                    '///返回值：var类型数据， 任意类型
                    '///注：下面各case中函数意义相同
                    Dim result_bool As Byte = plc.Read(dbaddress, db, startByteAdr, VarType.Byte, 1)
                    Dim read_result_bool As Byte = result_bool ';
                    Dim read_bool As Boolean = read_result_bool.SelectBit(bit_number) '; // SelectBit函数， 从字节中读取1位
                    If (read_bool = True) Then
                        Return "1"
                    End If
                    If (read_bool = False) Then
                        Return "0"
                    End If
                Case "Byte"   '   //无符号byte
                    Dim result_byte As Byte = plc.Read(dbaddress, db, startByteAdr, VarType.Byte, 1) ';
                    Dim read_byte As Byte = result_byte ';
                    Return read_byte.ToString() ';

                Case "SByte"    '  //有符号byte

                    Dim result_sbyte As Byte = plc.Read(dbaddress, db, startByteAdr, VarType.Byte, 1) ';
                    Dim read_result_sbyte As Integer = result_sbyte
                    If (read_result_sbyte > 127) Then

                        read_result_sbyte = read_result_sbyte - 256
                    End If
                    Dim read_sbyte As SByte = read_result_sbyte
                    Return (read_sbyte.ToString())

                Case "Word"     ' //无符号word
                    Dim result_word As UShort = plc.Read(dbaddress, db, startByteAdr, VarType.Word, 1)
                    Dim read_word As UShort = result_word

                    Return read_word.ToString()

                Case "Int"     ' //有符号word
                    Dim result_int As Short = plc.Read(dbaddress, db, startByteAdr, VarType.Int, 1)
                    Dim read_int As Short = result_int
                    Return read_int.ToString()

                Case "DWord"    '  //无符号DWord
                    Dim result_dword As Integer = plc.Read(dbaddress, db, startByteAdr, VarType.DWord, 1)
                    Dim read_dword As Integer = result_dword

                    Return result_dword.ToString()
                Case "DInt"  '     //有符号DWord
                    '//var result_dint = plc.Read(DataAddress_Choise, db, startByteAdr, VarType.DInt, 1);//这个函数有bug，只要是负数就显示-2147483648
                    Dim result_dint As Double = plc.Read(dbaddress, db, startByteAdr, VarType.DWord, 1)
                    Dim read_result_dint As Double = result_dint
                    If (read_result_dint > 2147483647) Then

                        read_result_dint = read_result_dint - 4294967296
                    End If
                    Dim read_dint As Integer = read_result_dint
                    DataRead_TextBox.Text = read_dint.ToString()

                Case "Real"
                    Dim result_real As Double = plc.Read(dbaddress, db, startByteAdr, VarType.Real, 4)
                    Dim read_real As Double = result_real
                    Return read_real.ToString()
            End Select
        End If
    End Function
    Function set_bit(data As Byte, index As Integer, flag As Boolean)

        '// if (index > 8 || index < 1) 该程序中不存在这种情况，如果移植他处请注意。
        '// throw New ArgumentOutOfRangeException();
        Dim v As Integer
        If index < 2 Then
            v = index
        Else

            v = (2 << (index - 2))
        End If
        If flag Then '
            Return data Or v
        Else
            Return data & Not v
        End If

    End Function
    Function writedata(write_value As String, dbnumber As String, dbaddress As DataType, dbtypestring As String, startaddress As String, bitnumber As String)

        If (Not plc.IsConnected) Then
            Return ("请先建立连接！")
        End If
        If (dbnumber = "") Then
            Return ("请先填写DB块号！")

        Else
            db = Convert.ToInt32(dbnumber)
        End If
        If (startaddress = "") Then
            Return ("请先填写偏移量！")

        Else
            startByteAdr = Convert.ToInt32(startaddress) ';//读取数据起始地址

            Select Case (dbtypestring)

                Case "Bool"
                    'Public ErrorCode Write(DataType dataType, int db, int startByteAdr, Object value)
                    '上面的函数写位数据有bug， 实现不了， 所以用下面的函数来写

                    '/使用下面的函数写位数据时就需要先读取1个字节，再将字节中的位，置0或1，再将该字节数据写回到PLC
                    Dim bit_number As Integer = Convert.ToInt32(bitnumber)
                    Dim result_bool As Byte = plc.Read(dbaddress, db, startByteAdr, VarType.Byte, 1)
                    Dim read_result_bool As Byte = result_bool
                    Dim write_bit_number As Byte = Convert.ToInt16(BitNumber_ComboBox.Text) + 1
                    Dim write_bool As Byte = 0
                    If (DataWrite_TextBox.Text = "1") Then
                        write_bool = set_bit(read_result_bool, write_bit_number, True)

                        If (DataWrite_TextBox.Text = "0") Then
                            write_bool = set_bit(read_result_bool, write_bit_number, False)

                            '/dbaddress数据区
                            '/int db：DB块号， 读写I、Q、M时都为0， 读写V区的时为1， 读写DB块时按实际情况处理
                            '/int startByteAdr：起始地址
                            '/write_bool：要写入的值， 这个值的数据类型要与所选的数据区的数据类型相符
                            '/注：下面各case中函数意义相同
                            Dim write_bool_result As String = plc.Write(dbaddress, db, startByteAdr, write_bool)
                        End If
                    End If


                Case "Byte"   '无符号byte
                    Dim write_byte As Byte = Convert.ToByte(write_value)
                    Dim write_byte_result As String = plc.Write(dbaddress, db, startByteAdr, write_byte)

                Case "SByte"   '有符号byte
                    Dim write_sbyte As Byte = Convert.ToSByte(write_value)
                    Dim write_sbyte_result As String = plc.Write(dbaddress, db, startByteAdr, write_sbyte)

                Case "Word"   '无符号Word
                    Dim write_word As UShort = Convert.ToUInt16(write_value)
                    Dim write_word_result As String = plc.Write(dbaddress, db, startByteAdr, write_word)

                Case "Int"   '有符号Word
                    Dim write_int As Short = Convert.ToInt16(write_value)
                    Dim write_int_result As String = plc.Write(dbaddress, db, startByteAdr, write_int)

                Case "DWord"   '无符号DWord
                    Dim write_dword As Integer = Convert.ToUInt32(write_value)
                    Dim write_dword_result As String = plc.Write(dbaddress, db, startByteAdr, write_dword)

                Case "DInt"   '有符号DWord
                    Dim write_dint As Integer = Convert.ToInt32(write_value)
                    Dim write_dint_result As String = plc.Write(dbaddress, db, startByteAdr, write_dint)

                Case "Real"
                    Dim write_real As Double = Convert.ToDouble(write_value)
                    Dim write_real_result As String = plc.Write(dbaddress, db, startByteAdr, write_real)

            End Select
            Return "写入完成"
        End If
    End Function
    Private Sub Disconnect_Button_Click(sender As Object, e As EventArgs) Handles Disconnect_Button.Click
        Connect_Label.Text = breakconnect()
    End Sub

    Private Sub DataType_ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DataType_ComboBox.SelectedIndexChanged
        If (DataType_ComboBox.Text = "Bool") Then
            DataType_Choise_string = "Bool"
            DataType_Choise = VarType.Byte
            Bit_Number_Label.Visible = True
            BitNumber_ComboBox.Visible = True

        ElseIf (DataType_ComboBox.Text = "Byte") Then
            DataType_Choise_string = "Byte"
            DataType_Choise = VarType.Byte
            Bit_Number_Label.Visible = False
            BitNumber_ComboBox.Visible = False

        ElseIf (DataType_ComboBox.Text = "SByte") Then
            DataType_Choise_string = "SByte"
            DataType_Choise = VarType.Byte
            Bit_Number_Label.Visible = False
            BitNumber_ComboBox.Visible = False

        ElseIf (DataType_ComboBox.Text = "Word") Then
            DataType_Choise_string = "Word"
            DataType_Choise = VarType.Word
            Bit_Number_Label.Visible = False
            BitNumber_ComboBox.Visible = False

        ElseIf (DataType_ComboBox.Text = "Int") Then
            DataType_Choise_string = "Int"
            DataType_Choise = VarType.Int
            Bit_Number_Label.Visible = False
            BitNumber_ComboBox.Visible = False

        ElseIf (DataType_ComboBox.Text = "DWord") Then
            DataType_Choise_string = "DWord"
            DataType_Choise = VarType.DWord
            Bit_Number_Label.Visible = False
            BitNumber_ComboBox.Visible = False

        ElseIf (DataType_ComboBox.Text = "DInt") Then
            DataType_Choise_string = "DInt"
            DataType_Choise = VarType.DInt
            Bit_Number_Label.Visible = False
            BitNumber_ComboBox.Visible = False

        ElseIf (DataType_ComboBox.Text = "Real") Then
            DataType_Choise_string = "Real"
            DataType_Choise = VarType.Real
            Bit_Number_Label.Visible = False
            BitNumber_ComboBox.Visible = False
        End If
    End Sub

    Private Sub DataAddress_ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DataAddress_ComboBox.SelectedIndexChanged
        If (DataAddress_ComboBox.Text = "I") Then
            DataAddress_Choise = DataType.Input
            DB_Number_Label.Visible = False
            DB_Number_TextBox.Visible = False
            DB_Number_TextBox.Text = "0"

        ElseIf (DataAddress_ComboBox.Text = "Q") Then
            DataAddress_Choise = DataType.Output
            DB_Number_Label.Visible = False
            DB_Number_TextBox.Visible = False
            DB_Number_TextBox.Text = "0"

        ElseIf (DataAddress_ComboBox.Text = "M") Then
            DataAddress_Choise = DataType.Memory
            DB_Number_Label.Visible = False
            DB_Number_TextBox.Visible = False
            DB_Number_TextBox.Text = "0"

        ElseIf (DataAddress_ComboBox.Text = "V") Then
            DataAddress_Choise = DataType.DataBlock
            DB_Number_Label.Visible = True
            DB_Number_TextBox.Visible = True
            DB_Number_TextBox.Text = "1"
            DB_Number_TextBox.ReadOnly = True

        ElseIf (DataAddress_ComboBox.Text = "DB") Then
            DataAddress_Choise = DataType.DataBlock
            DB_Number_Label.Visible = True
            DB_Number_TextBox.Visible = True
            DB_Number_TextBox.Text = "1"
            DB_Number_TextBox.ReadOnly = False

        Else DataAddress_Choise = DataType.Input
        End If
    End Sub

    Private Sub ReadData_Button_Click(sender As Object, e As EventArgs) Handles ReadData_Button.Click
        DataRead_TextBox.Text = readdata(DB_Number_TextBox.Text, DataAddress_Choise, DataType_Choise_string, DataAddress_TextBox.Text, BitNumber_ComboBox.Text)
    End Sub

    Private Sub WriteData_Button_Click(sender As Object, e As EventArgs) Handles WriteData_Button.Click
        MsgBox(writedata(DataWrite_TextBox.Text, DB_Number_TextBox.Text, DataAddress_Choise, DataType_Choise_string, DataAddress_TextBox.Text, BitNumber_ComboBox.Text))
    End Sub


    Private Sub Connect_Button_Click(sender As Object, e As EventArgs) Handles Connect_Button.Click

        Connect_Label.Text = (Remoteconnectplc(Plc_Choice_ComboBox.Text, Plc_IP_TextBox.Text, Plc_Rack_TextBox.Text, Plc_Slot_TextBox.Text))

    End Sub
    '******************************************【END】S7直连代码******************************************************
    '******************************************【BEGIN】多线程socket 最新******************************************************
    Dim st As Thread
    Public Delegate Sub ParameterizedThreadStart(obj As Object)
    Dim socketclass As New AsynchronousSocketListener
    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click

        Dim IPAddress As IPAddress   '定义IP地址
        Dim HostIP As IPHostEntry  '定义主机IP地址集
        'HostName = Dns.GetHostName ' 获取本地主机名称
        Dim port As String = TextBox5.Text


        'Dim localEndPoint As New IPEndPoint(IPAddress.Parse(Trim(ComboBox1.Text)), Trim(TextBox2.Text))  '''指定IP和Port

        HostIP = Dns.GetHostByName(Dns.GetHostName()) ' 获取本地主机的IP地址集

        IPAddress = New IPAddress(HostIP.AddressList(0).Address)

        Dim t As Object

        '在BtnStart的click事件中，加入如下代码:

        st = New Thread(AddressOf socketclass.Main))  '''建立新的线程

        st.Start({Trim(ComboBox1.Text), Trim(TextBox5.Text)})     '''启动线程
        Button5.Enabled = False   '''按钮不可用，避免另启线程

    End Sub
    Public Shared tagQueue As New Queue()
    Public Function invokeudpdateform(content As String)

        tagQueue.Enqueue(content)

        'Dim hander As New MyInvoke(AddressOf UpdateFormM)


        'Me.Invoke(hander, "接收到条码信息:" & content)


        'UpdateFormM(content)
    End Function

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Try

            AsynchronousSocketListener.listener.Close()     '''关闭Socket
            st.Abort()     '''中止线程

        Catch
        Finally
            Button5.Enabled = True   '''启用BtnStart

        End Try
    End Sub

    Private Sub TabPage5_Click(sender As Object, e As EventArgs) Handles TabPage5.Click

    End Sub

    Function UpdateFormM(param1 As String) '//定义一个更新窗体方法
        RichTextBox3.AppendText(param1 & Chr(13))
        RichTextBox3.ScrollToCaret()

    End Function

    Private Sub TabPage5_Enter(sender As Object, e As EventArgs) Handles TabPage5.Enter
        启动非阻塞socket接收()
        'ComboBox1.DataSource = HostIP.AddressList
        '      ComboBox1.DisplayMember = "Address"
    End Sub
    Function 启动非阻塞socket接收()
        '获取当前网络信息
        Dim HostIP As IPHostEntry  '定义主机IP地址集
        Dim IPAddress As IPAddress
        HostIP = Dns.GetHostByName(Dns.GetHostName()) ' 获取本地主机的IP地址集
        ComboBox1.Items.Clear()

        For i = 0 To HostIP.AddressList.Count - 1

            IPAddress = New IPAddress(HostIP.AddressList(i).Address)

            ComboBox1.Items.Add(IPAddress.ToString)
            ComboBox1.Text = (IPAddress.ToString)
        Next

        '开启线程，循环处理
        Dim kk As Threading.Thread
        kk = New Threading.Thread(New Threading.ThreadStart(AddressOf readdata))
        kk.IsBackground = True
        kk.Start()
        '通信状态监测
        Timer1.Enabled = True

    End Function
    Function readdata()
        While True
            While tagQueue.Count > 0
                Dim content As String
                content = tagQueue.Dequeue

                Dim hander As New MyInvoke(AddressOf UpdateFormM)


                '        Me.Invoke(hander, "接收到条码信息:" & content)
                Me.Invoke(hander, "接收到PLC信息:" & content & Chr(13) & "处理信息:" & Mid(content, 40, 66))
                dealdata(content)
                'Me.Invoke(New ShowListViewCallBack(AddressOf UpdateView), tag)

            End While

        End While

    End Function

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        If imsocket_lasttime.AddMinutes(1) < Now And Label19.Text <> "socket未连接" Then
            Label19.Text = "socket未连接"
            'IMME_notice.notice_show("系统提醒", "即时消息", "PLC通信已断开", "很不幸的通知您,产线PLC通信已断开,请检查相关网络连接是否正常,如有报错产生，请向上级反馈")

        End If
        If imsocket_lasttime.AddMinutes(1) > Now And Label19.Text <> "socket正在通讯" Then
            Label19.Text = "socket正在通讯"
        End If
    End Sub

    Function dealdata(content As String)
        Dim dealresult As String = ""
        'author:lxfamn date:20200910 descrip:socket通讯
        '机械手西门子modbus协议处理约定：
        '前40位为modbus协议报头。往后每6位（不含空格4位）例如“_00_01”为一个16进制标识位，第一位为业务标识位
        '托盘车转运业务（业务标识： 00 01）：
        '指令示例：转运请求： 00 01 00 01 ；倒筐请求： 00 01 00 02；倒筐不产生空框：00 01 00 03
        '第一标识位" 00 01"时为，托盘车业务标识；后期若有其他模块业务新增可新增标识如“ 00 02”
        '第二标识位" 00 01"时为，发送转运请求；第二标识位" 00 02"时为，发送倒筐请求；第二标识位" 00 03"时为，发送倒筐请求不产生空筐；
        Dim stringA As String = Mid(content, 40, 66)
        If Mid(stringA, 1, 6) = " 00 01" Then
            If Mid(stringA, 7, 6) = " 00 01" Then
                dealresult = dealresult & "|"
            End If
            If Mid(stringA, 7, 6) = " 00 02" Then
                dealresult = dealresult & "|"
            End If
            If Mid(stringA, 7, 6) = " 00 03" Then
                dealresult = dealresult & "|"
            End If

        End If
        'author:lxfamn date:20200910 descrip:socket通讯
        '机械手三菱处理约定（暂定）：
        'PLC以ASC码形式传递数据，字符串格式为“A|1|...."；字符串以“|”间隔，第一位为业务标识位
        '托盘车转运业务（业务标识：10）：
        '指令示例：转运请求：(FF|FF)|1|10|10；倒筐请求：(FF|FF)|1|10|20；倒筐不产生空框：(FF|FF)|1|10|30
        '第一标识位"10"时为，托盘车业务标识；后期若有其他模块业务新增可新增标识如“20|”
        '第二标识位"10"时为，发送转运请求；第二标识位"20"时为，发送倒筐请求；第二标识位"30"时为，发送倒筐请求不产生空筐；

        If InStr(content, "|") > 0 Then
            Dim stringB() As String = Split(content, "|")
            If stringB(3) = "10" Then
                If stringB(4) = "10" Then
                    dealresult = dealresult & "|"
                End If
                If stringB(4) = "20" Then
                    dealresult = dealresult & "|"
                End If
                If stringB(4) = "30" Then
                    dealresult = dealresult & "|"
                End If

            End If
        End If

        Dim hander As New MyInvoke(AddressOf UpdateFormM)

        Me.Invoke(hander, "数据处理结果:" & dealresult)
    End Function

    Private Sub TabPage3_Click(sender As Object, e As EventArgs) Handles TabPage3.Click

    End Sub

    Private Sub IMCO_SocketPLC_Shown(sender As Object, e As EventArgs) Handles Me.Shown

    End Sub

End Class
